package org.elanfox.intellicommunity.common.httputil;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;

import java.util.Map;

/**
 * 网络请求助手
 *
 * @author guomw
 */
public class HttpClientHelper {
    private static final Log log = LogFactory.getLog(HttpClientHelper.class);

    /**
     * post 请求
     *
     * @param cls
     * @param url
     * @param requestMap
     * @param header
     * @return
     */
    public static <T> T post(Class<T> cls, String url, Map<String, String> requestMap, Map<String, String> header) {
        try {
            HttpResult httpResult = HttpClientUtil.post(url, requestMap, header);
            if (httpResult.getHttpStatus() == HttpStatus.SC_OK) {
                return JSONObject.parseObject(httpResult.getHttpContent(), cls);
            }
        } catch (Exception e) {
            log.error("HttpClientHelper.post", e);
        }
        return null;
    }

    /**
     * post
     *
     * @param cls
     * @param url
     * @param requestMap
     * @return
     */
    public static <T> T post(Class<T> cls, String url, Map<String, String> requestMap) {
        return post(cls, url, requestMap, null);
    }


    /**
     * post 请求
     *
     * @param cls
     * @param url
     * @param requestData
     * @param header
     * @return
     */
    public static <T> T post(Class<T> cls, String url, String requestData, Map<String, String> header) throws Exception {
        HttpResult httpResult = HttpClientUtil.post(url, requestData, header);
        if (httpResult.getHttpStatus() == HttpStatus.SC_OK) {
            return JSONObject.parseObject(httpResult.getHttpContent(), cls);
        } else {
            throw new Exception(httpResult.getHttpContent());
        }
    }

    /**
     * post
     *
     * @param cls
     * @param url
     * @param requestData
     * @return
     */
    public static <T> T post(Class<T> cls, String url, String requestData) throws Exception {
        return post(cls, url, requestData, null);
    }
}
